/*
 * 创建日期 2009-12-14
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.head;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;

import  org.fantasy.common.cache.Caches;
import  org.fantasy.common.cache.service.resource.TableConfig;
import  org.fantasy.common.grid.bean.Column;

/**
 * XML配置表头
 * @author: 王文成
 * @version: 1.0
 * @since 2009-12-14
 */
public class TableHeadXml extends BaseTableHead {

	private static final Log log = LogFactory.getLog(TableHeadXml.class);

	public TableHeadXml(HttpServletRequest request, String tableConfig) throws Exception {
		super(request, tableConfig);
	}

	/**
	 * 取得Table节点
	 * 
	 * @return
	 */
	@Override
	@SuppressWarnings("unchecked")
	protected Element getTableElement() throws Exception {
		Map<Object, TableConfig> tableMap = (Map<Object, TableConfig>) Caches.RESOURCE.getTableConfigCache(request);
		TableConfig config = tableMap.get(tableConfig);
		Document document = config.getDoc();
		// 如果未配置表头
		if (document == null)
			throw new JspException(">>>>>>> 未找到表头配置，请检查配置文件 [tableConfig=" + config + "]");

		Element root = document.getRootElement();
		List<Element> list = root.selectNodes("/table[@name]");
		Element table = list.get(0);
		return table;
	}

	@Override
	public List<String> getSumCols() throws Exception {
		List<String> sumCols = new ArrayList<String>();
		List<Column> list = super.getTableFields();
		for (Column column : list) {
			if ("true".equalsIgnoreCase(column.getIsSum())) {
				sumCols.add(column.getFieldName());
			}
		}
		return sumCols;
	}

	@Override
	public List<String> getStatCols() throws Exception {
		List<String> statCols = new ArrayList<String>();
		List<Column> list = super.getTableFields();
		for (Column column : list) {
			if ("true".equalsIgnoreCase(column.getIsStat())) {
				statCols.add(column.getFieldName());
			}
		}
		return statCols;
	}

	@Override
	public String getSubTotal() throws Exception {
		Element table = getTableElement();
		return table.attributeValue("subTotal");
	}

	@Override
	public String getSumTotal() throws Exception {
		Element table = getTableElement();
		return table.attributeValue("sumTotal");
	}
}
